package cn.metona.mq.security;

import cn.metona.mq.config.ConfigManager;

import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

/**
 * 认证管理器
 * 提供基本的认证和授权功能
 */
public class AuthManager {
    private static final Logger logger = Logger.getLogger(AuthManager.class.getName());
    
    private static final AuthManager INSTANCE = new AuthManager();
    
    private final ConcurrentHashMap<String, User> users;      // 用户映射
    private final ConcurrentHashMap<String, String> tokens;   // 令牌映射
    private final boolean securityEnabled;
    
    private AuthManager() {
        this.users = new ConcurrentHashMap<>();
        this.tokens = new ConcurrentHashMap<>();
        ConfigManager configManager = ConfigManager.getInstance();
        this.securityEnabled = configManager.getBooleanProperty("mq.security.enabled", false);
        
        if (securityEnabled) {
            initializeDefaultUsers();
        }
    }
    
    public static AuthManager getInstance() {
        return INSTANCE;
    }
    
    /**
     * 初始化默认用户
     */
    private void initializeDefaultUsers() {
        // 添加默认管理员用户
        addUser("admin", "admin123", UserRole.ADMIN);
        addUser("user", "user123", UserRole.USER);
        logger.info("Default users initialized");
    }
    
    /**
     * 添加用户
     */
    public void addUser(String username, String password, UserRole role) {
        if (!securityEnabled) {
            return;
        }
        
        User user = new User(username, hashPassword(password), role);
        users.put(username, user);
        logger.info("User added: " + username);
    }
    
    /**
     * 用户认证
     */
    public String authenticate(String username, String password) {
        if (!securityEnabled) {
            return "anonymous";
        }
        
        User user = users.get(username);
        if (user == null) {
            throw new SecurityException("User not found: " + username);
        }
        
        if (!verifyPassword(password, user.getPasswordHash())) {
            throw new SecurityException("Invalid password for user: " + username);
        }
        
        // 生成令牌
        String token = generateToken(username);
        tokens.put(token, username);
        logger.info("User authenticated: " + username);
        return token;
    }
    
    /**
     * 验证令牌
     */
    public boolean validateToken(String token) {
        if (!securityEnabled) {
            return true;
        }
        
        if (token == null || token.isEmpty()) {
            return false;
        }
        
        return tokens.containsKey(token);
    }
    
    /**
     * 获取用户角色
     */
    public UserRole getUserRole(String token) {
        if (!securityEnabled) {
            return UserRole.ADMIN; // 默认管理员权限
        }
        
        String username = tokens.get(token);
        if (username == null) {
            return UserRole.ANONYMOUS;
        }
        
        User user = users.get(username);
        return user != null ? user.getRole() : UserRole.ANONYMOUS;
    }
    
    /**
     * 检查权限
     */
    public boolean checkPermission(String token, Permission permission) {
        if (!securityEnabled) {
            return true;
        }
        
        UserRole role = getUserRole(token);
        return role.hasPermission(permission);
    }
    
    /**
     * 注销用户
     */
    public void logout(String token) {
        if (!securityEnabled) {
            return;
        }
        
        tokens.remove(token);
        logger.info("User logged out");
    }
    
    /**
     * 密码哈希
     */
    private String hashPassword(String password) {
        // 简单的哈希实现（实际应用中应使用更安全的算法）
        return Integer.toString(password.hashCode());
    }
    
    /**
     * 验证密码
     */
    private boolean verifyPassword(String password, String hash) {
        return hashPassword(password).equals(hash);
    }
    
    /**
     * 生成令牌
     */
    private String generateToken(String username) {
        return username + "_" + System.currentTimeMillis() + "_" + 
               Integer.toHexString(username.hashCode());
    }
    
    /**
     * 用户类
     */
    public static class User {
        private final String username;
        private final String passwordHash;
        private final UserRole role;
        
        public User(String username, String passwordHash, UserRole role) {
            this.username = username;
            this.passwordHash = passwordHash;
            this.role = role;
        }
        
        public String getUsername() { return username; }
        public String getPasswordHash() { return passwordHash; }
        public UserRole getRole() { return role; }
    }
    
    /**
     * 用户角色枚举
     */
    public enum UserRole {
        ADMIN, USER, ANONYMOUS;
        
        public boolean hasPermission(Permission permission) {
            return switch (this) {
                case ADMIN -> true; // 管理员拥有所有权限
                case USER -> permission != Permission.ADMIN; // 普通用户不能执行管理操作
                default -> false;
            };
        }
    }
    
    /**
     * 权限枚举
     */
    public enum Permission {
        READ, WRITE, ADMIN
    }
}